package edu.nps.ai.agent;

import java.util.List;
import java.util.Map;

import edu.nps.ai.astar.AStar;
import edu.nps.ai.astar.Point;

/**
 * @author Timothy Riley
 */
public class LabThreeAgent extends AbstractAgent {
	/**
	 * Holds the phrase to search for a command
	 */
	private static final String GO_TO_LOCATION = "go to the ";

	/**
	 * Initialize the environment
	 *
	 * @param host
	 *            The host name of the server
	 * @param port
	 *            The port the server is running one
	 * @param userName
	 *            The user name to create in the environment
	 * @param password
	 *            The password for the user created
	 * @param delay
	 *            The delay between commands
	 * @param logFile
	 *            The log file
	 */
	public LabThreeAgent(final String host, final Integer port, final String userName, final String password, final Integer delay, final String logFile) {
		initialize(host, port, userName, password, delay, logFile);
	}

	/**
	 * @see edu.nps.ai.agent.Agent#execute()
	 */
	public void execute() {
		AStar astar = getAstar();
		Map<String, Point> pointMap = astar.getPointMap();
		while (true) {
			List<String> output = listen();
			String toNode = goToNode(output);
			if (toNode != null && pointMap.containsKey(toNode)) {
				send("say ok");
				String currentNode = location();
				List<String> navigationCommands = astar.search(currentNode, toNode);
				for (String command : navigationCommands) {
					send(command);
				}
			}
		}
	}

	/**
	 * Helper method to search the output for the phrase "go to X"
	 * Where X is the location to navigate to
	 * @param output
	 * @return The node to navigate to or null if not found
	 */
	private String goToNode(final List<String> output) {
		if (output == null) {
			throw new IllegalArgumentException("The output is requried");
		}
		String node = null;
		for (String line : output) {
			if (line.contains(GO_TO_LOCATION)) {
				Integer gotoIndex = line.indexOf(GO_TO_LOCATION);
				node = line.substring(gotoIndex + GO_TO_LOCATION.length(), line.length() - 1);
				log("Going to node [" + node + "]");
				break;
			}
		}
		return node;
	}

	/**
	 * Main method to execute the agent
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length != 6) {
			throw new IllegalArgumentException("Wrong number of command line arguments!");
		}
		String hostName = args[0];
		Integer port = Integer.parseInt(args[1]);
		String userName = args[2];
		String password = args[3];
		Integer delay = Integer.parseInt(args[4]);
		String logFile = args[5];
		LabThreeAgent lab = new LabThreeAgent(hostName, port, userName, password, delay, logFile);
		lab.execute();
	}
}